<template>
  <div class="container">
    <el-card>
      <div slot="header">
        <span>试题录入</span>
      </div>
      <el-form
        ref="form"
        style="width: 300px"
        :model="form"
        label-width="120px"
        :rules="rules"
      >
        <el-form-item label="学科 :" prop="subjectID">
          <el-select
            style="width: 400px"
            size="medium"
            @change="onChange"
            v-model="form.subjectID"
            placeholder="请选择"
          >
            <el-option
              v-for="itm in ArrObj.subjectName"
              :key="itm.value"
              :label="itm.label"
              :value="itm.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录 :" prop="catalogID">
          <el-select
            style="width: 400px"
            size="medium"
            v-model="form.catalogID"
            placeholder="请选择"
          >
            <el-option
              v-for="itm in ArrObj.catalogName"
              :key="itm.value"
              :label="itm.label"
              :value="itm.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业 :" prop="enterpriseID">
          <el-select
            style="width: 400px"
            size="medium"
            v-model="form.enterpriseID"
            placeholder="请选择"
          >
            <el-option
              v-for="itm in ArrObj.enterpriseArr"
              :key="itm.id"
              :label="itm.company"
              :value="itm.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市 :" prop="province">
          <el-select
            style="width: 48%"
            v-model="form.province"
            placeholder="请选择"
            @change="changeFn"
          >
            <el-option
              v-for="(itm, i) in ArrObj.provinces"
              :key="i"
              :label="itm"
              :value="itm"
            ></el-option>
          </el-select>
          <el-select
            v-model="form.city"
            style="width: 50%; margin-left: 2%"
            placeholder="请选择"
          >
            <el-option
              v-for="(itm, i) in ArrObj.citys"
              :key="i"
              :label="itm"
              :value="itm"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="方向 :" prop="direction">
          <el-select
            style="width: 400px"
            size="medium"
            v-model="form.direction"
            placeholder="请选择"
          >
            <el-option
              v-for="(itm, i) in ArrObj.direction"
              :key="i"
              :label="itm"
              :value="itm"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题型 :" prop="questionType">
          <el-radio-group v-model="form.questionType">
            <el-radio label="1">单选</el-radio>
            <el-radio label="2">多选</el-radio>
            <el-radio label="3">简答</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难度 :" prop="difficulty">
          <el-radio-group v-model="form.difficulty">
            <el-radio label="1">简单</el-radio>
            <el-radio label="2">一般</el-radio>
            <el-radio label="3">困难</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题干 :" prop="answer">
          <template>
            <div id="text-box"></div>
          </template>
        </el-form-item>

        <el-form-item
          label="选项 :"
          v-if="form.questionType === '2' || form.questionType === '1'"
        >
          <el-checkbox-group
            v-model="checkList"
            v-if="form.questionType === '2'"
          >
            <div v-for="itm in arrList" :key="itm.code">
              <el-checkbox :label="itm.code"> {{ itm.code }} : </el-checkbox>
              <el-row style="display: inline-block; width: 230px">
                <el-input v-model="itm.title"></el-input>
              </el-row>
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :http-request="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                style="display: inline-block; position: relative;vertical-align: middle;"
              >
                <div class="avatar-uploader-icon" @click="test(itm.code)">
                  <img v-if="itm.img" :src="itm.img" class="avatar" />
                  <span v-else >上传图片</span>
                </div>
                <i class="el-icon-circle-close aaa"></i>
              </el-upload>
            </div>
          </el-checkbox-group>
          <el-radio-group v-model="radio" v-if="form.questionType === '1'">
            <div v-for="itm in arrList" :key="itm.code" style="height: 75px">
              <el-radio :label="itm.code">{{ itm.code }} :</el-radio>
              <el-row style="display: inline-block; width: 230px">
                <el-input v-model="itm.title"></el-input>
              </el-row>
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :http-request="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                style="display: inline-block; position: relative;vertical-align: middle;"
              >
                <div class="avatar-uploader-icon">
                  <img v-if="itm.img" :src="itm.img" class="avatar" />
                  <span v-else>上传图片</span>
                </div>
                <i class="el-icon-circle-close aaa"></i>
              </el-upload>
            </div>
          </el-radio-group>
          <el-row>
            <el-button
              type="danger"
              size="mini"
              :disabled="form.questionType === '1' || arrList.length === 8"
              @click="onAdd"
              >+增加选项与答案</el-button
            >
          </el-row>
        </el-form-item>
        <el-form-item label="解析视频:">
          <el-row>
            <el-input v-model="form.videoURL"></el-input>
          </el-row>
        </el-form-item>
        <el-form-item label="答题解析:" prop="question">
          <template>
            <div id="text-box2"></div>
          </template>
        </el-form-item>
        <el-form-item label="题目备注:">
          <template>
            <el-input v-model="form.remarks" type="textarea" :rows="4">
            </el-input>
          </template>
        </el-form-item>
        <el-form-item label="试题标签">
          <template>
            <el-select
              style="width: 400px"
              size="medium"
              v-model="form.tags"
              placeholder="请选择"
            >
              <el-option
                v-for="itm in ArrObj.tags"
                :key="itm.value"
                :label="itm.label"
                :value="itm.label"
              >
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item>
          <template>
            <el-button type="primary" @click="onSubimt">确认提交</el-button>
          </template>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import E from 'wangeditor'
import { simple } from '@/api/hmmm/subjects.js'
import { list } from '@/api/hmmm/companys'
import { provinces, citys } from '@/api/hmmm/citys'
import { simple as simples } from '@/api/hmmm/directorys'
import { simple as simpleb } from '@/api/hmmm/tags'
import arrList from '@/api/hmmm/arrList'
import { direction } from '@/api/hmmm/constants'
import { add } from '@/api/hmmm/questions'
let Gethtml = ''
let Gethtml1 = ''

const COS = require('cos-js-sdk-v5')
const cos = new COS({
  SecretId: 'AKIDAC0bx4xb0A4mGVXL0TjkV1IJ5cuxlJch', // 身份识别ID
  SecretKey: 'sUr0tXyCBuOddOtHapz3FQP9evxmPrES' // 身份秘钥
})

export default {
  data () {
    return {
      aaaa: true,
      form: {
        catalogID: '', // 目录
        subjectID: '', // 学科
        province: '', // 城市
        city: '',
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        enterpriseID: '',
        tags: '',
        options: [],
        videoURL: '',
        answer: '',
        question: '',
        remarks: ''
      },
      rules: {
        subjectID: [{ required: true, message: '请输入内容!', trigger: 'change' }],
        catalogID: [{ required: true, message: '请输入内容!', trigger: 'change' }],
        enterpriseID: [{ required: true, message: '请输入内容!', trigger: 'change' }],
        province: [{ required: true, message: '请输入内容!', trigger: 'change' }],
        direction: [{ required: true, message: '请输入内容!', trigger: 'change' }],
        questionType: [{ required: true, message: '请输入内容!', trigger: 'change' }],
        answer: [{ required: true, message: '请输入内容!', trigger: 'change' }],
        question: [{ required: true, message: '请输入内容!', trigger: 'change' }],
        difficulty: [{ required: true, message: '请输入内容!', trigger: 'change' }]
      },
      ArrObj: {
        subjectName: [],
        enterpriseArr: [],
        provinces: provinces(),
        citys: [],
        tags: [],
        catalogName: [],
        direction
      },
      imageUrl: '',
      arrList,
      checkList: [],
      checkInput: '',
      radio: '',
      num: 0,
      arrType: ''
    }
  },
  async created () {
    const res = await simple() // 学科
    this.ArrObj.subjectName = res.data
    const arr = await list({ pagesize: 100 })
    this.ArrObj.enterpriseArr = arr.data.items
    const editor = new E('#text-box')
    editor.config.zIndex = 0
    editor.config.height = 240
    editor.config.customUploadImg = function (resultFiles, insertImgFn) {
      // resultFiles 是 input 中选中的文件列表
      // insertImgFn 是获取图片 url 后，插入到编辑器的方法
      // 执行上传操作
      cos.putObject(
        {
          Bucket: 'zhaozhao-1307367217' /* 存储桶 */,
          Region: 'ap-beijing' /* 存储桶所在地域，必须字段 */,
          Key: resultFiles[0].name /* 文件名 */,
          StorageClass: 'STANDARD', // 上传模式, 标准模式
          Body: resultFiles[0], // 上传文件对象;
          onProgress: (progressData) => {
            console.log(JSON.stringify(progressData))
          }
        },
        (err, data) => {
          console.log(err || data)
          // 上传成功之后
          if (data.statusCode === 200) {
            insertImgFn(`http://${data.Location}`)
          }
        }
      )
      // 上传图片，返回结果，将图片插入到编辑器中
      // insertImgFn(imgUrl)
    }
    editor.create()
    editor.config.onchange = function (newHtml) {
      Gethtml = newHtml
    }
    const editor1 = new E('#text-box2')
    editor1.config.zIndex = 0
    editor1.config.height = 240
    editor1.config.customUploadImg = function (resultFiles, insertImgFn) {
      // resultFiles 是 input 中选中的文件列表
      // insertImgFn 是获取图片 url 后，插入到编辑器的方法
      // 执行上传操作
      cos.putObject(
        {
          Bucket: 'zhaozhao-1307367217' /* 存储桶 */,
          Region: 'ap-beijing' /* 存储桶所在地域，必须字段 */,
          Key: resultFiles[0].name /* 文件名 */,
          StorageClass: 'STANDARD', // 上传模式, 标准模式
          Body: resultFiles[0], // 上传文件对象;
          onProgress: (progressData) => {
            console.log(JSON.stringify(progressData))
          }
        },
        (err, data) => {
          console.log(err || data)
          // 上传成功之后
          if (data.statusCode === 200) {
            insertImgFn(`http://${data.Location}`)
          }
        }
      )
      // 上传图片，返回结果，将图片插入到编辑器中
      // insertImgFn(imgUrl)
    }
    editor1.create()
    editor1.config.onchange = function (newHtml) {
      Gethtml1 = newHtml
    }
  },
  methods: {
    test (type) {
      this.arrType = type
    },
    onAdd () {
      const add = ['E', 'F', 'G', 'H']
      this.arrList.push({
        isRight: true,
        code: `${add[this.num]}`,
        title: '',
        img: ''
      })
      this.num++
    },
    async onSubimt () {
      this.form.question = Gethtml
      this.form.answer = Gethtml1
      const arr = this.arrList.map((itm) => {
        if (this.form.questionType === '1') {
          if (itm.code === this.radio) {
            itm.isRight = 1
          } else {
            itm.isRight = 0
            itm.title = ''
            itm.img = ''
          }
        } else {
          if (this.checkList.includes(itm.code)) {
            itm.isRight = 1
          } else {
            itm.isRight = 0
            itm.title = ''
            itm.img = ''
          }
        }
        return itm
      })
      this.form.options = arr
      const newArr = {}
      for (const key in this.form) {
        if (this.form[key]) {
          newArr[key] = this.form[key]
        }
      }
      this.$refs.form.validate(async vali => {
        if (vali) {
          await add(newArr)
          this.$router.push('/questions/list')
        }
      })
    },
    async onChange (id) {
      const res = await simples({ id })
      this.ArrObj.catalogName = res.data
      const arr = await simpleb({ id })
      this.ArrObj.tags = arr.data
    },
    changeFn (type) {
      this.form.city = ''
      this.ArrObj.citys = citys(type)
    },
    handleAvatarSuccess (res, file, item) {
      console.log(item, res)
      cos.putObject(
        {
          Bucket: 'zhaozhao-1307367217' /* 存储桶 */,
          Region: 'ap-beijing' /* 存储桶所在地域，必须字段 */,
          Key: res.file.name /* 文件名 */,
          StorageClass: 'STANDARD', // 上传模式, 标准模式
          Body: res.file, // 上传文件对象;
          onProgress: (progressData) => {
            console.log(JSON.stringify(progressData))
          }
        },
        (err, data) => {
          console.log(err || data)
          const arr = this.arrList.map((itm) => {
            if (this.form.questionType === '1') {
              if (itm.code === this.radio) {
                itm.img = `http://${data.Location}`
              } else {
                itm.img = ''
              }
            } else { // 问题解决
              if (this.arrType === itm.code) {
                itm.img = `http://${data.Location}`
              }
            }
            return itm
          })
          console.log(arr)
          this.form.options = arr
          this.arrList = arr
        }
      )
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style scoped lang='scss'>
.aaa {
  position: absolute;
  font-size: 18px;
  top: -6px;
  right: -6px;
}
.el-radio {
  margin-right: 20px;
}
.container {
  padding: 20px;
}
::v-deep .el-form-item__content {
  width: 400px;
}
#text-box,
#text-box2 {
  width: 270%;
}

.avatar-uploader .el-upload {
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader-icon {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  font-size: 14px;
  color: #8c939d;
  width: 100px;
  height: 60px;
  line-height: 60px;
  display: inline-block;
  text-align: center;
  margin-left: 8px;
}
.avatar {
  width: 100%;
  height: 100%;
  display: inline-block;
}
.el-checkbox {
  margin: 20px 9px;
}
</style>
